<?php
require(dirname(dirname(__FILE__))."/Config/config.php");
require(dirname(dirname(__FILE__))."/jssdk.php");
require(dirname(dirname(dirname(__FILE__)))."/Qiaqia/Core/WxPay.Exception.php");

class wxpayController extends appController{
	private $configUlr;
	public $wxid = 0;//数据库Id
	
	public $m;//自己的model
	public $info=array();//当前用户的微信信息
	public  function __construct(){
		parent::__construct();
		//基础信息构建
		$this->configUlr =  ROOT_PATH."Mobile/Config/yaotv.json";
		$this->m = Model('wxpay');
		//微信分享参数构建
		$jsdk = $this->m ->get_jsdk();
	
		$this->assign("signPackage", $jsdk);
	
		//当前用户的微信id
		$this->wxid = $_SESSION['wxid']?$_SESSION['wxid']:0;
	
		if($this->wxid>0)
		{
			//当前用户的微信信息
			$this->info = $this->m->get_record($this->wxid);
			$this->assign('info',$this->info);
		}
	}
	public function index(){
		if(!isset($_SESSION['wxid']))
		{
			//是否已授权
			$this->check_member();
		}else{
			$this->assign("index.html");
		}
	}
	
	/**
	 * 预下单
	 */
	public function beforehandPay(){
		$path = $$this->configUlr;
		$json = json_decode(file_get_contents($path), true);
		$result = $this->assembledData($json);
		if($result['return_code']!="SUCCESS"||$result['result_code']!="SUCCESS"){
// 			header('Location:');
			$resu = array("error"=>1);
			print_r(json_encode($resu));
		}else{
			$res = array(
					"appId" 	=> $json['appid'],
					"nonceStr"	=> hy_rand(16),
					"package"	=> "prepay_id=".$result['prepay_id'],
					"signType"	=> "SHA1",
					"timestamp"	=> yf_time()
			);
			$stringA = $this->ToUrlParams($res)."&key=".$json['key'];
			$sign=strtoupper(sha1($stringA));
			$res['paySign'] = $sign;
			$resu = array("error"=>0);
			$resu['result'] = $res;
			print_r(json_encode($res));
		}
	}
	
	private function assembledData($json){
		$nonce_str = hy_rand(32);
// 		$out_trade_no = $json['mch_id'].date("YmdHis");
		$out_trade_no = $this->m->get_out_trade_no($json['mch_id']);
		$time_start = date("YmdHis");
		$time = time()+900;
		$time_expire = date("YmdHis",$time);
		$spbill_create_ip = hy_getIP();
		$signData = array(
				"appid"  			=> $json['appid'],
				"body"				=> "小王子体验馆门票--凭卡券到现场兑换成人票一张",
				"detail"			=> "凭卡券可到小王子中国行活动现场换领入场门票",
				"mch_id" 			=> $json['mch_id'],
				"nonce_str" 		=> $nonce_str,
				"notify_url"		=> $json['notify_url'],
				"openid"			=> $this->info['openid'],
				"out_trade_no"		=> $out_trade_no,
				"spbill_create_ip"	=> $spbill_create_ip,
				"time_expire"		=> $time_expire,
				"time_start"		=> $time_start,
				"total_fee"			=> 1,
				"trade_type"		=> $json['trade_type']
		);
		$stringA = $this->ToUrlParams($signData)."&key=".$json['key'];
		$sign=strtoupper(md5($stringA));
		$signData['sign'] = $sign;
		
		$str = "<xml>
				   <appid>$signData[appid]</appid>
				   <body>$signData[body]</body>
				   <detail>$signData[detail]</detail>
				   <mch_id>$signData[mch_id]</mch_id>
				   <nonce_str>$signData[nonce_str]</nonce_str>
				   <notify_url>$signData[notify_url]</notify_url>
				   <openid>$signData[openid]</openid>
				   <out_trade_no>$signData[out_trade_no]</out_trade_no>
				   <spbill_create_ip>$signData[spbill_create_ip]</spbill_create_ip>
				   <time_expire>$signData[time_expire]</time_expire>
				   <time_expire>$signData[time_expire]</time_expire>
				   <total_fee>$signData[total_fee]</total_fee>
				   <trade_type>$signData[trade_type]</trade_type>
				   <sign>$signData[sign]</sign>
				</xml>";
		
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		$result=$this->post_it($url, $str);
		$result=(array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
		if($result['return_code']=="SUCCESS"&&$result['result_code']=="SUCCESS"){
			$info['wxid'] = $this->wxid;
			$info['time_start'] = $signData['time_start'];
			$info['time_expire'] = $signData['time_expire'];
			$info['total_fee'] = $signData['total_fee'];
			$info['out_trade_no'] = $signData['out_trade_no'];
			$info['prepay_id'] = $result['prepay_id'];
			$info['pay_status'] = "NOTPAY";
			$this->m->insert($info,"wx_pay");
		}else{
			
		}
		return $result;
	}
	
	/**
	 * 用post方法获取数据
	 * @param $url
	 * @param $data
	 * @return
	 */
	public function post_it($url, $data)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);
		if($result){
			curl_close($curl);
			return $result;
		}
		else {
			$error = curl_errno($curl);
			curl_close($ch);
			return false;
		}
	}
	//回调
	public function notify(){
		//获取通知的数据
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		try {
			$path = $this->configUlr;
			$json = json_decode(file_get_contents($path), true);
			if(!$xml){
				throw new WxPayException("xml数据异常！");
			}
			libxml_disable_entity_loader(true);
			$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
			
			ksort($values);
			$string = $this->ToUrlParams();
			//签名步骤二：在string后加入KEY
			$string = $string . "&key=".$json['key'];
			//签名步骤三：MD5加密
			$string = md5($string);
			//签名步骤四：所有字符转为大写
			$result = strtoupper($string);
			if($this->GetSign() != $values['sign']){
				throw new WxPayException("签名错误！");
			}
			//加上逻辑操作
			if($values["return_code"]=="SUCCESS"&&$values["result_code"]=="SUCCESS"){
				$payId = $this->m->get_wx_pay_by_trade($values['out_trade_no']);
				if($payId){
					$info['pay_status'] = "SUCCESS";
					$info['transaction_id'] = $values['transaction_id'];
					$this->m->update($info,array("id"=>$payId,"table"=>"wx_pay"));
				}
			}
			$xml = "<xml>
			<return_code><![CDATA[SUCCESS]]></return_code>
			<return_msg><![CDATA[OK]]></return_msg>
			</xml>";
			echo $xml;
		} catch (WxPayException $e){
			$m= $e->errorMessage();
			$xml = "<xml>
			  <return_code><![CDATA[FAIL]]></return_code>
			  <return_msg><![CDATA[$m]]></return_msg>
			</xml>";
			echo $xml;
		}
	}
	
	
	public function ToUrlParams(){
		$buff = "";
		foreach ($this->values as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	/**
	 * 此功能主要是再去确认支付订单是否已经支付
	 * 返回值为true，表示已经支付
	 * false，表示未支付
	 */
	public function orderquery(){
		$transaction_id = $_GET['transaction_id'];
		$path = $this->configUlr;
		$json = json_decode(file_get_contents($path), true);
		$nonce_str = hy_rand(16);
		$signData = array(
				"appid"  			=> $json['appid'],
				"mch_id" 			=> $json['mch_id'],
				"nonce_str"			=> $nonce_str,
				"transaction_id" 	=> $transaction_id,
		);
		$stringA = $this->ToUrlParams($signData)."&key=".$json['key'];
		$sign=strtoupper(md5($stringA));
		$signData['sign'] = $sign;
		$str = "<xml>
				   <appid>$signData[appid]</appid>
				   <mch_id>$signData[mch_id]</mch_id>
				   <nonce_str>$signData[nonce_str]</nonce_str>
				   <transaction_id>$signData[transaction_id]</transaction_id>
				   <sign>$signData[sign]</sign>
				</xml>";
		$result=$this->post_it($url, $str);
		$result=(array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
		if($result['return_code']=="SUCCESS"&&$result['result_code']=="SUCCESS"){
			if($result['trade_state'] =="SUCCESS"){
				//判断是否已经修改，如果是的话，不修改
				if($this->m->is_pay($result['out_trade_no'])){
					return true;
				}else{//不是已经支付的话,修改为支付，跳转至领取卡券页面
					$info['pay_status'] = "SUCCESS";
					$id = $this->m->get_id_by_trade($result['out_trade_no']);
					$this->m->update($info,array("table"=>"wx_pay","id"=>$id));
					return true;
				}
				
			}
			
		}
		return false;
	}
	
}